import type { PaginationConfig, PaginationState, PageResponse } from '@/types'

/**
 * 创建标准的分页配置
 * @param options 分页选项
 * @returns 分页配置对象
 */
export function createPaginationConfig(options: {
  current?: number
  pageSize?: number
  total?: number
  forwardOnly?: boolean
} = {}): PaginationConfig {
  const {
    current = 1,
    pageSize = 10,
    total = 0,
    forwardOnly = false
  } = options

  return {
    current,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: !forwardOnly, // 仅向前模式时禁用快速跳转
    showTotal: (total: number, range: [number, number]) =>
      forwardOnly
        ? `已加载 ${range[1]} 条数据`
        : `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
  }
}

/**
 * 从API响应创建分页配置
 * @param pageResponse API分页响应
 * @param supportPrevious 是否支持向前翻页
 * @returns 分页配置对象
 */
export function createPaginationFromResponse<T>(
  pageResponse: PageResponse<T>,
  supportPrevious = true
): PaginationConfig {
  return {
    current: pageResponse.current,
    pageSize: pageResponse.size,
    total: pageResponse.total,
    showSizeChanger: true,
    showQuickJumper: supportPrevious,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
  }
}

/**
 * 创建分页状态管理器
 * @param pageResponse API分页响应
 * @param previousCursors 前面页面的游标栈
 * @returns 分页状态
 */
export function createPaginationState<T>(
  pageResponse: PageResponse<T>,
  previousCursors: number[] = []
): PaginationState {
  return {
    current: pageResponse.current,
    pageSize: pageResponse.size,
    total: pageResponse.total,
    pages: pageResponse.pages,
    hasNext: pageResponse.hasNext,
    nextCursor: pageResponse.nextCursor,
    previousPageCursors: [...previousCursors]
  }
}

/**
 * 处理分页导航
 * @param state 当前分页状态
 * @param direction 导航方向 'next' | 'prev'
 * @param currentLastId 当前页面的起始lastId
 * @returns 新的查询参数
 */
export function handlePaginationNavigation(
  state: PaginationState,
  direction: 'next' | 'prev',
  currentLastId: number = 0
): { lastId: number; current: number; previousCursors: number[] } {
  if (direction === 'next') {
    // 向前翻页：记录当前页的lastId，使用nextCursor
    const newPreviousCursors = [...state.previousPageCursors, currentLastId]
    return {
      lastId: state.nextCursor,
      current: state.current + 1,
      previousCursors: newPreviousCursors
    }
  } else {
    // 向后翻页：使用记录的前一页lastId
    const newPreviousCursors = [...state.previousPageCursors]
    const prevLastId = newPreviousCursors.pop() || 0
    return {
      lastId: prevLastId,
      current: Math.max(1, state.current - 1),
      previousCursors: newPreviousCursors
    }
  }
}

/**
 * 表格的中文locale配置
 */
export const tableLocale = {
  emptyText: '暂无数据'
}
